﻿$(function () {
    var pageSize = 15;
//    home();
//    prev();
//    next();
//    goPage();
    
/*	var username = window.sessionStorage.getItem("username");

	if (username == null || username == undefined || username == ''){
		
		location.href = "login.html";
	}*/
    
// 	$('#logout').click(function() {
// 		//清除session
// 		sessionStorage.clear();
// //		window.location.href="login.html";
// 		$.ajax({
// 			type : "post",
// 			url : "../servlet/ClearSessionServlet",
// 			dataType : "json",
// 			success : function(data) {
// 			    if(data.msg=="clear"){
// 			    	window.location.href="login.html";
// 			    }
//
// 			}
// 		});
// 	})
	
    // $('#export').click(function () {
    //
    // 	var starttime = $('#starttime').val();
    // 	var endtime = $('#endtime').val();
    // 	var carno = $('#carno').val();
    // 	var pname = $('#pname').val();
    // 	location.href="servlet/ExcelExportServlet?starttime="+starttime+
    // 	"&endtime="+endtime+
    // 	"&carno="+carno+
    // 	"&pname="+encodeURI(encodeURI(pname));
    // });
    
    
    $('#find').click(function () {
    	selectPage(1);
    	//$('#list').show();
    });

    //首页
    $("#homePage").click(function () {
        $("#paging").text(1);
        selectPage(1);
    });
    
    //尾页
    $("#lastPage").click(function () {
    	//总页数
    	var countText=$('#countPage').text();
        //类型转换
        var countNum = parseInt(countText);
        $("#paging").text(countNum);
        selectPage(countNum);
    });
    
    //去到第几页
    $("#goPage").click(function () {
        var pageNum=parseInt($("#pageNum").val());
        var countPage=parseInt($("#countPage").text())
        //判断超出了总页码
        if(pageNum>countPage){
            selectPage(countPage);
            $("#paging").text(countPage);
            $("#pageNum").val(countPage);
            alert("超出最大页码数,显示尾页!");
            return;
        }
        //判断低于了总页码
        if(pageNum<1){
            selectPage(1);
            $("#paging").text(1);
            $("#pageNum").val(1);
            alert("输入页码不合法，显示首页!");
            return;
        }
        selectPage(pageNum);
        $("#paging").text(pageNum);
    });
    
    //上一页
    $('#prevPage').click(function () {
        var prevText=$('#paging').text();
        var prevNum=parseInt(prevText);
        prevNum=prevNum-1;
        if(prevNum<=1){
            selectPage(1);
            $('#paging').text(1);
            return;
        }
        $("#paging").text(prevNum);
        selectPage(prevNum);
    });
   
    //下一页
    $('#nextpage').click(function () {
    	//获取文本的值 页数
        var prevText=$('#paging').text();
        //类型转换
        var prevNum=parseInt(prevText);
        //总页数
        var countText=$('#countPage').text();
        //类型转换
        var countNum = parseInt(countText);
        //页数加1
        prevNum=prevNum+1;
        //判断超出了总页码
        if(prevNum>=countNum){
            selectPage(countNum);
            $('#paging').text(countNum);
            return;
        }
        //设置网页增加的值
        $('#paging').text(prevNum);
        //调用分页查询
        selectPage(prevNum);
    	
    });
    
    
    function selectPage(pageCode) {
    	
    	var startDate = $('#startDate').val();
    	var endDate = $('#endDate').val();
    	var carno = $('#carno').val();
    	var pname = $('#pname').val();
    	var options = $("#area option:selected");
    	var area = options.val();
    	//var area = $('#area').val();

    	if(startDate==""||startDate==null){
    		
//    		$('body').alert({
//    		type: 'warning',
//    		content:'开始日期不能为空!'
//    		});
//    		return;
			swal("开始时间不能为空!");
			return;

    	}
    	if(endDate==""||endDate==null){
    		
//    		$('body').alert({
//    		type: 'warning',
//    		content:'结束日期不能为空!'
//    		});
//    		return;
			swal("结束时间不能为空!");
			return;
    	}
    	

        //分页查询 pageCode：页数
        $.ajax({
			type : "post",
			url : "/WeightBridge/weightDetailData",
			data:{"pageIndex":pageCode,"pageSize":pageSize,"startDate":startDate,"endDate":endDate,"carno":carno,"pname":pname,"area":area},
			dataType : "json",
			success : function(data) {
//				var bill_objRecords = eval("(" + redata.result + ")");
//				maxItems = eval("(" + redata.count + ")");
				$("#detail").html("");
				$("#detail #data").html("");
                //总页数
                $("#countPage").text(data.totalPage);
                $("#totalCount").text(data.totalCount);
//				for (var i = 0; i < data.result.length; i++) {
//
//                    $("#detail").append(
//                        "<tr>\n" +
//                        "<td>"+data.result[i].ticketno+"</td>\n" +
//                        "<td>"+data.result[i].carno+"</td>\n" +
//                        //"<td>"+dateFormat(data.result[i].grosstime,"")+"</td>\n" +
//                        "<td>"+data.result[i].grosstime+"</td>\n" +
//                        "<td>"+data.result[i].netweight+"</td>\n" +
//                        "<td>"+data.result[i].productname+"</td>\n" +
//                        "<td>"+data.result[i].username+"</td>\n" +
//                        "<td>"+data.result[i].iccode+"</td>\n" +
//                        "</tr>"
//                    );
//				}
                if(data.result.length<=0){
                    $('tfoot').find("th").eq(3).text("");
                    $('#datatable-buttons').dataTable().fnClearTable();
                	swal("查询失败！", "未查询到满足条件的结果！");
                }
                else{
                	
    				$('#datatable-buttons').dataTable().fnClearTable();
    				$('#datatable-buttons').dataTable().fnAddData(packagingdatatabledata(data),true);
                    $('#datatable-buttons').dataTable().fnSort([[2, 'desc']]);

                }


			}
		});
        
        
    }
   
   function packagingdatatabledata(data){
   
	   var editHtml='<button href="#modal-container-648308" rel="external nofollow" data-toggle="modal" class="btn btn-xs btn-info" onclick="test_env_modify(this)"> <i class="icon-edit bigger-120"></i> </button> <button href="#modal-container-648300" rel="external nofollow" data-toggle="modal" class="btn btn-xs btn-danger" onclick="test_env_delete(this)"> <i class="icon-trash bigger-120"></i> </button>';

	   var a=[]; //全部行数据的list
	   var banddata = data.result;
	   for(var key in banddata){
	     var tempObj=[];  //一行数据的list
	 	 var actionHtml='<input data-id ="'+banddata[key].ticketno+'" class="btn" id="update" type="button" value="修改"/>';
	     tempObj.push(banddata[key].ticketno);
	     tempObj.push(banddata[key].carno);
	     tempObj.push(dateFormat(banddata[key].grosstime,""));
	     tempObj.push(banddata[key].netweight);
	     tempObj.push(banddata[key].productname);
	     tempObj.push(banddata[key].username);
	     tempObj.push(banddata[key].iccode);
	     tempObj.push(banddata[key].syqy);
	     tempObj.push(banddata[key].bz);
	     // tempObj.push(actionHtml);
	     //tempObj.push(editHtml);
	     a.push(tempObj);
	    }
 	   return a;

   }
   
   //修改
   $('#datatable-buttons')
	.on('click', '#update', function( e ) {

    	var tno = $(this).attr("data-id");
    	$(this).parents().parents().children("td").eq(3).attr("contentEditable","true");
    	$(this).attr("style","display:none;");
    	$(this).parents().parents().children("td").eq(8).html("<input data-id='"+tno+"' class='btn' id='save' type='button' value='保存' />"+"\n"+"<input data-id='"+tno+"' class='btn' id='cancel' type='button' value='取消' />"+"\n");

    	
    	
	})

	//取消
   $('#datatable-buttons').on('click', '#cancel', function( e ) {

	   	var tno = $(this).attr("data-id");
		$(this).parents().parents().children("td").eq(3).attr("contentEditable","false");
		$(this).attr("style","display:block;");
		$(this).parents().parents().children("td").eq(8).html("<input data-id='"+tno+"' class='btn' id='update' type='button' value='修改' />"+"\n");

    	
    	
	})
	
	
	//保存
	$('#datatable-buttons').on('click', '#save', function( e ) {
		
		
		var weight = $(this).parents().parents().children("td").eq(3).text();
    	var ticketno = $(this).attr("data-id");
        $.ajax({
			type : "post",
			url : "../servlet/EditDbServlet",
			data:{"weight":weight,"ticketno":ticketno},
			dataType : "json",
			success : function(data) {

				if(data.result==true){
					
			        swal("保存成功!", "", "success");
			        
					$('#save').parents().parents().children("td").eq(3).attr("contentEditable","false");
					$('#save').parents().parents().children("td").eq(8).html("<input data-id='"+ticketno+"' class='btn' id='update' type='button' value='修改' />"+"\n");

				}
				else{
					
					swal("保存失败！", "请检查输入数据格式！"); 

				}

			}
		});
    	
    	
	})
   
   
    /**
     * 日期格式化
     * @param Number time 时间戳
     * @param String format 格式
     */
    function dateFormat (time, format) {
      const t = new Date(time)
      // 日期格式
      format = format || 'Y-m-d h:i:s'
      let year = t.getFullYear()
      // 由于 getMonth 返回值会比正常月份小 1
      let month = t.getMonth() + 1
      let day = t.getDate()
      let hours = t.getHours()
      let minutes = t.getMinutes()
      let seconds = t.getSeconds()

      const hash = {
        'y': year,
        'm': month,
        'd': day,
        'h': hours,
        'i': minutes,
        's': seconds
      }
      // 是否补 0
      const isAddZero = (o) => {
        return /M|D|H|I|S/.test(o)
      }
      return format.replace(/\w/g, o => {
        let rt = hash[o.toLocaleLowerCase()]
        return rt >= 10 || isAddZero(o) ? rt : `0${rt}`
      })
    }

})